using System.IO;
using System.Text;

namespace FemtoHttpd
{
    public class ChunkedResponse : FemtoHttpResponse
    {
        public delegate void Func2<T>(T arg);

        private static readonly byte[] CRLF = new byte[] { (byte)'\r', (byte)'\n' };
        private static readonly byte[] ZERO_CRLF = new byte[] { (byte)'0', (byte)'\r', (byte)'\n' };
        private static byte[] X_CRLF(int len, out byte[] buff)
        {
            return buff = Encoding.ASCII.GetBytes(len.ToString("x") + "\r\n");
        }

        public ChunkedResponse(Stream output) : base(output) 
        {
            Header["Transfer-Encoding"] = "chunked";
        }
        public Func2<ChunkedResponse> WriteContentImpl { set; get; }

        protected override void WriteContent()
        {
            WriteContentImpl?.Invoke(this);
            WriteEndBlock();
        }

        public void WriteChunkedBlock(byte[] data, int offset, int len)
        {
            Output.Write(X_CRLF(len - offset, out var buff), 0, buff.Length);
            Output.Write(data, offset, len);
            Output.Write(CRLF, 0, CRLF.Length);
        }
        private void WriteEndBlock()
        {
            Output.Write(ZERO_CRLF, 0, ZERO_CRLF.Length);
            Output.Write(CRLF, 0, CRLF.Length);
        }
    }
}
